package com.ruoyi.project.system.controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.service.SysLoginService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SmAutonomy;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.dto.ThrEleResult;
import com.ruoyi.project.system.domain.vo.UserProductPriceVo;
import com.ruoyi.project.system.mapper.SmProductMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISmProductService productService;

    @Autowired
    private ISmIncomeService iSmIncomeService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private ISmQueryService queryService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SmProductMapper smProductMapper;

    @Autowired
    private RedisCache redisCache;


    @PreAuthorize("@ss.hasPermi('system:user:upgrade')")
    @Log(title = "用户升级", businessType = BusinessType.UPDATE)
    @PutMapping("/upgrade")
    public AjaxResult upgradeUser(@NotNull Long userId, @NotNull Integer roleId) {
        return toAjax(userMapper.upgradeUser(userId, roleId));
    }

    @Anonymous
    @GetMapping("/invite")
    public AjaxResult inviteCode(String type, String ic) {
        return success(userMapper.queryRegisterAreaCode(type, ic));
    }

    /**
     * 查询推广首页
     */
    @Anonymous
    @GetMapping("/index")
    public AjaxResult index() {
        AjaxResult result = new AjaxResult();
        result.putAll(productService.index());
        result.put("income", iSmIncomeService.index());
        result.put("serveImg", smProductMapper.img("service"));
        result.put("swiperImg", smProductMapper.allImg("swiper"));
        return result;
    }

    @GetMapping("/teamMember")
    public AjaxResult teamMember() {
        Long userId = SecurityUtils.getUserId();
        return success(userMapper.queryMember(userId));
    }

    @GetMapping("/getIC")
    public AjaxResult getInviteCode(@NotBlank String info) {
        Long userId = SecurityUtils.getUserId();
        return success(productService.inviteCode(userId, info));
    }

    @GetMapping("/updateIC")
    public AjaxResult updateInviteCode(@NotBlank String olc) {
        String newInviteCode = IdUtils.fastSimpleUUID().substring(0, 6);
        userMapper.updateInviteCode(newInviteCode, olc);
        return success(newInviteCode);
    }

    @GetMapping("/payMentAccount")
    public AjaxResult payMentAccount() {
        Map<String, String> map = userMapper.selectAliAccount(SecurityUtils.getUserId());
        if (map == null) {
            return warn("未填写提现账户信息");
        } else {
            return success(map);
        }
    }

    /**
     * 验证修改收款账户
     */
    @PutMapping("/setPayMentAccount")
    public AjaxResult setPayMentAccount(@RequestBody Map<String, String> params) {
        if (StringUtils.isEmpty(params.get("code"))) {
            return AjaxResult.error("验证码为空");
        } else if (StringUtils.isEmpty(params.get("alipayName"))) {
            return AjaxResult.error("支付宝姓名为空");
        } else if (StringUtils.isEmpty(params.get("alipayAccount"))) {
            return AjaxResult.error("支付宝账号为空");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + SecurityUtils.getUsername();
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (!params.get("code").equals(captcha)) {
            return AjaxResult.error("验证码错误");
        }
        return success(userService.updateUser(new SysUser(SecurityUtils.getUserId(), params.get("alipayName"), params.get("alipayAccount"))));
    }

    @GetMapping("/teamStatistics")
    public AjaxResult teamStatistics() {
        AjaxResult result = new AjaxResult();
        Long userId = SecurityUtils.getUserId();
        result.put("people", userMapper.teamNumberOfPeople(userId));
        result.put("query", userMapper.teamNumberOfQuery(userId));
        result.put("income", userMapper.teamNumberOfIncome(userId));
        return result;
    }

    /**
     * 获取用户身份信息
     */
    @GetMapping("/member")
    public AjaxResult member() {
        AjaxResult result = new AjaxResult();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer roleId = user.getRoleId();
        result.put("roleName", roleService.selectRoleById(roleId.longValue()).getRoleName());
        return result;
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/productPriceList")
    public TableDataInfo productPriceList(@NotBlank SysUser user) {
        startPage();
        List<SysUser> users = userMapper.selectUserList_(user);
        List<UserProductPriceVo> userProductPriceVos = userService.selectUserProductVoList(users);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(userProductPriceVos);
        rspData.setTotal(new PageInfo(users).getTotal());
        return rspData;
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userMapper.selectUserList_(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        roleService.checkRoleDataScope(user.getRoleId());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        roleService.checkRoleDataScope(user.getRoleId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    @Anonymous
    @GetMapping("/pwdVerifyCode")
    public AjaxResult pwdVerifyCode(@NotBlank String tel) {
        SysUser info = userMapper.checkUserNameUnique(tel);
        if (info == null) {
            return error("电话号码未注册！");
        }
        return sysLoginService.sendVerifyCode(tel);
    }

    @Anonymous
    @GetMapping("/findPassword")
    public AjaxResult findPassword(@NotBlank String userName,
                                   @NotBlank String password,
                                   @NotBlank String comfirmPassword,
                                   @NotBlank String code) {
        AjaxResult verifyCode = sysLoginService.checkVerifyCode(userName, code);
        if ((int) verifyCode.get("code") == 200) {
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
                return warn("密码长度必须在5到20个字符之间");
            }
            if (password.equals(comfirmPassword)) {
                return warn("两次密码不一致");
            }
            SysUser info = userMapper.checkUserNameUnique(userName);
            if (info == null) {
                return error("电话号码（账号）未注册！");
            }
            return toAjax(userMapper.resetUserPwd(userName, SecurityUtils.encryptPassword(password)));
        } else {
            return verifyCode;
        }
    }

    @Anonymous
    @GetMapping("/autonomy")
    public AjaxResult autonomy(@NotBlank String name,
                               @NotBlank String cardNo,
                               @NotBlank String userName,
                               @NotBlank String code) {
        AjaxResult verifyCode = sysLoginService.checkVerifyCode(userName, code);
        if ((int) verifyCode.get("code") == 200) {
            ThrEleResult thrEleResult = queryService.verificationThrEle(new SmAutonomy(name, cardNo, userName));
            queryService.autonomy(thrEleResult.getSmAutonomy());
            if (thrEleResult.isPass()) {
                return success(thrEleResult.getMsg());
            } else {
                return warn(thrEleResult.getMsg());
            }
        } else {
            return verifyCode;
        }
    }

}

